<?php

namespace app\api\controller;


use app\admin\model\BuildingRoomModel;
use app\admin\model\UserChatModel;
use app\common\controller\Api;
use think\Db;
use think\Exception;


class Chat extends Api
{

    protected $noNeedRight = '*';


    public function user_list()
    {
        $page_size = $this->request->param('page_size/d', 10);
        $room_id = $this->request->param('room_id/d', 0);
        $homeowner_id = $this->request->param('homeowner_id/d', 0);

        if (!$homeowner_id) {
            $homeowner_id = BuildingRoomModel::getRoomOwner($room_id);
        }

        $where = [
            'user_id' => $this->auth->id,
            'homeowner_id' => $homeowner_id,
            'message_type' => 1,
        ];

        $this->user_read($homeowner_id);

        $list = UserChatModel::where($where)
            ->field('user_type,content,create_time,images')
            ->order('id', 'desc')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['create_time_text']);
                /*if ($item['images']) {
                    $images = explode(',', $item['images']);
                    foreach ($images as &$image) {
                        $image = cdnurl($image);
                    }
                    unset($image);
                    $item['images'] = $images;
                }*/
            })->toArray();

        $list['data'] = array_reverse($list['data']);

        $this->success('success', $list);
    }


    public function owner_list()
    {
        $page_size = $this->request->param('page_size/d', 10);
        $user_id = $this->request->param('user_id/d', 0);


        $where = [
            'user_id' => $user_id,
            'homeowner_id' => $this->auth->id,
            'message_type' => 1,
        ];

        $this->owner_read($user_id);
        $list = UserChatModel::where($where)
            ->field('user_type,content,create_time,images')
            ->order('id', 'desc')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['create_time_text']);
            })->toArray();

        $list['data'] = array_reverse($list['data']);

        $this->success('success', $list);
    }


    public function user_owner_list()
    {
        $user_id = $this->auth->id;
        $user_ids = UserChatModel::where(['user_id'=>$user_id,'message_type' => 1])->column('distinct homeowner_id');
        $list = \app\common\model\User::whereIn('id', $user_ids)
            ->field('id,nickname,avatar')
            ->select();

        foreach ($list as $item) {
            $message = UserChatModel::where([
                'user_id' => $user_id,
                'homeowner_id' => $item['id'],
                'message_type' => 1,
            ])->order('id', 'desc')->find();

            $item->message = $message['content'] ?? '';
            if (empty($item->message) && !empty($message->images)) {
                $item->message = '[图片]';
            }
            $item->message_time = empty($message) ? '' : $message['create_time'];
            $item->unread_num = $this->getUserUnreadNum($item['id']);
        }

        $this->success('success', $list);
    }

    public function owner_user_list()
    {
        $owner_user_id = $this->auth->id;
        $user_ids = UserChatModel::where(['homeowner_id' =>$owner_user_id, 'message_type' => 1])->column('distinct user_id');
        $list = \app\common\model\User::whereIn('id', $user_ids)
            ->field('id,nickname,avatar')
            ->select();

        foreach ($list as $item) {
            $message = UserChatModel::where([
                'user_id' => $item['id'],
                'homeowner_id' => $owner_user_id,
                'message_type' => 1,
            ])->order('id', 'desc')->find();

            $item->message = $message['content'] ?? '';
            if (empty($item->message) && !empty($message->images)) {
                $item->message = '[图片]';
            }
            $item->message_time = empty($message) ? '' : $message['create_time'];

            $item->unread_num = $this->getOwnerUnreadNum($item['id']);
        }

        $this->success('success', $list);
    }

    public function user_send()
    {
        $params = $this->request->only('room_id,content,images,homeowner_id');

        if (empty($params['room_id']) && empty($params['homeowner_id'])) {
            $this->error('room_id和homeowner_id必须传一个');
        }

        if (empty($params['content']) && empty($params['images'])) {
            $this->error('发送数据不能为空');
        }
        if (count(explode(',', $params['images'])) > 9) {
            $this->error('最多9张图片');
        }
        $params['content'] = filter_words($params['content'] ?? '');
        $params['user_id'] = $this->auth->id;
        $params['user_type'] = 1;
        if (empty($params['homeowner_id']) && !empty($params['room_id'])) {
            $params['homeowner_id'] = BuildingRoomModel::getRoomOwner($params['room_id']);
        }

        if (empty($params['homeowner_id'])) {
            $this->error('未获取到房东信息');
        }
        $res = UserChatModel::create($params, true);

        if ($res) {
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }
    }


    public function owner_send()
    {
        //$this->checkIsHouseOwner();
        $params = $this->request->only('user_id,content,images');
        $checkRes = $this->validate($params, [
            'user_id|用户ID' => 'require',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        if (empty($params['content']) && empty($params['images'])) {
            $this->error('发送数据不能为空');
        }
        if (count(explode(',', $params['images'])) > 9) {
            $this->error('最多9张图片');
        }
        $params['user_type'] = 2;
        $params['homeowner_id'] = $this->auth->id;
        $params['content'] = filter_words($params['content'] ?? '');
        $res = UserChatModel::create($params, true);

        if ($res) {
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }
    }

    private function getOwnerUnreadNum($user_id = 0)
    {
        $where = [
            'user_type' => 1,
            'homeowner_id' => $this->auth->id,
            'is_read' => 0,
            'message_type' => 1,
        ];
        if ($user_id) {
            $where['user_id'] = $user_id;
        }
        return UserChatModel::where($where)->count();
    }

    private function getUserUnreadNum($owner_id = 0)
    {
        $where = [
            'user_type' => 2,
            'user_id' => $this->auth->id,
            'is_read' => 0,
            'message_type' => 1,
        ];
        if ($owner_id) {
            $where['homeowner_id'] = $owner_id;
        }
        return UserChatModel::where($where)->count();
    }


    public function owner_unread_num()
    {
        $this->success('成功', $this->getOwnerUnreadNum());
    }

    public function user_unread_num()
    {
        $this->success('成功', $this->getUserUnreadNum());
    }

    public function user_read($owner_id = 0)
    {

        //$owner_id = $this->request->param('owner_id/d', 0);

        UserChatModel::update([
            'is_read' => 1
        ], [
            'user_type' => 2,
            'user_id' => $this->auth->id,
            'homeowner_id' => $owner_id,
            'create_time' => ['<', time()],
            'message_type' => 1,
        ]);

        //$this->success('成功');
    }

    public function owner_read($user_id = 0)
    {
        //$user_id = $this->request->param('user_id/d', 0);

        UserChatModel::update([
            'is_read' => 1
        ], [
            'user_type' => 1,
            'user_id' => $user_id,
            'homeowner_id' => $this->auth->id,
            'create_time' => ['<', time()],
            'message_type' => 1,
        ]);

        //$this->success('成功');
    }



    public function user_to_user_send()
    {
        $params = $this->request->only('content,images,to_user_id');

        if (empty($params['to_user_id'])) {
            $this->error('to_user_id不能为空');
        }

        if (empty($params['images'])) {
            $params['images'] = '';
        }

        if (empty($params['content']) && empty($params['images'])) {
            $this->error('发送数据不能为空');
        }
        if ($params['images'] && count(explode(',', $params['images'])) > 9) {
            $this->error('最多9张图片');
        }
        $params['content'] = filter_words($params['content'] ?? '');
        $params['user_id'] = $this->auth->id;
        $params['homeowner_id'] = $params['to_user_id'];
        $params['message_type'] = 2;
        $params['user_type'] = 1;

        $res = UserChatModel::create($params, true);

        if ($res) {
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }
    }

    public function user_to_user_list()
    {
        $user_id = $this->auth->id;
        $message_type = 2;
        $chat_list = UserChatModel::where([
            'user_id|homeowner_id' => $user_id,
            'message_type' => $message_type
        ])->field('user_id,homeowner_id')
            ->select();
        $user_ids = array_merge(array_column($chat_list, 'user_id'), array_column($chat_list, 'homeowner_id'));
        $list = \app\common\model\User::whereIn('id', $user_ids)
            ->field('id,nickname,avatar')
            ->select();

        foreach ($list as $item) {
            $to_user_id = $item['id'];
            $message = UserChatModel::where([
                'message_type' => $message_type,
            ])
                ->where(function ($query) use ($to_user_id) {
                    $query->where(function ($q) use ($to_user_id) {
                        $q->where([
                            'user_id' => $this->auth->id,
                            'homeowner_id' => $to_user_id,
                        ]);
                    })->whereOr(function ($q) use ($to_user_id) {
                        $q->where([
                            'user_id' => $to_user_id,
                            'homeowner_id' => $this->auth->id,
                        ]);
                    });
                })
                ->order('id', 'desc')->find();

            $item->message = $message['content'] ?? '';
            if (empty($item->message) && !empty($message->images)) {
                $item->message = '[图片]';
            }
            $item->message_time = empty($message) ? '' : $message['create_time'];
            $item->unread_num = $this->getUserToUserUnreadNum($item['id']);
        }

        $this->success('success', $list);
    }


    private function getUserToUserUnreadNum($from_id = 0)
    {
        $where = [
            'homeowner_id' => $this->auth->id,
            'is_read' => 0,
            'message_type' => 2,
        ];

        if ($from_id) {
            $where['user_id'] = $from_id;
        }

        return UserChatModel::where($where)->count();
    }

    public function user_to_user_unread_num()
    {
        $this->success('成功', $this->getUserToUserUnreadNum());
    }

    public function user_to_user_chat_list()
    {
        $page_size = $this->request->param('page_size/d', 10);
        $to_user_id = $this->request->param('to_user_id/d', 0);

        UserChatModel::update([
            'is_read' => 1
        ], [
            'user_id' => $to_user_id,
            'homeowner_id' => $this->auth->id,
            'message_type' => 2,
        ]);

        $where = [
            'message_type' => 2,
        ];
        $list = UserChatModel::where($where)
            ->where(function ($query) use ($to_user_id) {
                $query->where(function ($q) use ($to_user_id) {
                    $q->where([
                        'user_id' => $this->auth->id,
                        'homeowner_id' => $to_user_id,
                    ]);
                })->whereOr(function ($q) use ($to_user_id) {
                    $q->where([
                        'user_id' => $to_user_id,
                        'homeowner_id' => $this->auth->id,
                    ]);
                });
            })
            ->field('user_id as from_user_id,homeowner_id as to_user_id,content,create_time,images')
            ->order('id', 'desc')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['create_time_text']);
                $is_self = 0;
                if ($item['from_user_id'] == $this->auth->id) {
                    $is_self = 1;
                }
                $item->is_self = $is_self;
            })->toArray();

        $list['data'] = array_reverse($list['data']);

        $this->success('success', $list);
    }
}
